#####################################################################
# Product:      KnowledgeEngine (Plone Edition)
#
# File:         AssessmentActions.py
#
# Copyright:    Copyright (c) 2008, Faulkner Technologies
#
# Author:       James Davies
#
#####################################################################

#####################################################################
## Knowledge Engine Library Imports
from Products.KnowledgeEngine.Common import *
from Products.KnowledgeEngine.Core import *
from Products.KnowledgeEngine.Elements.Toolbar.ToolbarTool import ToolbarTool, ToolbarToolInfo
from Products.KnowledgeEngine.PropertyDefinition import *
from Products.KnowledgeEngine.PropertyTypes import *
from Products.KnowledgeEngine.PropertyFormats import *
from Products.KnowledgeEngine.PropertyStructures import *

#####################################################################
## Zope Library Imports
from Globals import DTMLFile
from App.ImageFile import ImageFile


#####################################################################
## AssessmentActionsInfo Class Definition
class AssessmentActionsInfo(ToolbarToolInfo):
    """
        Defines the class info methods, defining information about
        the class without needing an instance of the class
    """
    
    #---------------------------------------------------------------#
    
    def getClassName(self):
        """
            Returns the name of the class for which 
            we are providing information.
        """
        return "AssessmentActions"

    #---------------------------------------------------------------#

    def getDisplayName(self):
        """
            Return a friendly name for the class instances
            (this is used for displaying in lists etc)
        """
    
        return "Assessment Actions"
        
    #---------------------------------------------------------------#

    def getIdentityType(self):
        """
            Return the identity type.  
        """
        
        return "toolActions"
        
    #---------------------------------------------------------------#
    
    def getClassIcon(self):
        """
            Return the appropriate icon file for the class.
        """
        
        return ImageFile('skins/AssessmentActions_icon.png', globals())
        
    #---------------------------------------------------------------#

    def isPermittedInContainer(self, containerClassInfo, containerInstance = None, instance=None):
        """
            ABSTRACT: Returns if class instances (instance) is permitted in 
            the specified container (containerInstance)
            
            NOTE: This is from this class' instance perspective.
        """
        
        #DEFAULT RULE: AssessmentActionss are only permitted in Toolbars
        return containerClassInfo.isInstanceOf('Toolbar') and ((containerInstance == None) or (containerInstance != None and len(containerInstance.getChildrenByInstanceOf(self.getClassName())) == 0))
    
    #---------------------------------------------------------------#

    def onConfigureProperties(self):
        """
            Automatically called by the Knowledge Engine once
            the class has been loaded.  Use this method to register 
            class specific properties using the PropertyReflection interface.
            
            If this class is sub-classed, a call must be made to
            the super-class to ensure super-class properties are
            correctly registered
            
            NOTE: This method is called before ClassInfo.onAfterStartup()            
        """

        #initialise the super-class properties for reflection
        ToolbarToolInfo.onConfigureProperties(self)
        
        self.addPropertyDefinition(PropertyDefinition(
            identity="displayMode", 
            displayName="Display Mode", 
            description="How should assessment actions be displayed", 
            propertyType=pt_STRING, 
            propertyFormat=pf_NATIVE, 
            hasEnumeratedValues=true, 
            enumeratedValuesList=["Buttons","Dropdown"], 
            defaultValue="Buttons",
        ))
        
        #set the default id
        self.getPropertyDefinition('id').setDefaultValue('actions')
                        

    #---------------------------------------------------------------#

#####################################################################
## AssessmentActions Class Definition
class AssessmentActions(ToolbarTool):
    """
        A class to represent a button in a toolbar
    """

    #---------------------------------------------------------------#

    #ABSTRACT TRANSIENT: a ClassInfo implementation instance to provide info about this class
    _CLASSINFO = AssessmentActionsInfo()

    #---------------------------------------------------------------#

    # Custom zope manage_preview to permit previews of components.
    preview_html = DTMLFile('index_html', globals())

    #---------------------------------------------------------------#

    def __init__(self, id, identity):
        "Constructor for the AssessmentActions"        

        ToolbarTool.__init__(self, id, identity)
        
        #perform onAfterInstanciation processing
        self.onAfterInstanciation()

    #---------------------------------------------------------------#

    def onAfterInstanciation(self):
        """
            Handle Knowledge Engine specific actions after this object 
            has been loaded into memory.  
            
            This is useful for performing backwards compatibility
        """        
        
        #perform default processing
        ToolbarTool.onAfterInstanciation(self)
        
    #---------------------------------------------------------------#

    def isPreviewPermitted(self):
        """
            Return if the Element is allowed to be previewed.
            
            By default all elements can't be previewed, some however
            should can be previewed. eg: HTMLHeaderFooters
        """
        
        return true
        
    #---------------------------------------------------------------#
   

    def getContent(self, contentZone, forGenericObject = None, assessment = None):
        """
            Return the Element generated 
            content for the specified contentZone (a string).   

            This method is called by the Model.index_html dtml file
            to customise the appearance of the output.
            
            By overriding this method, Elements have the opportunity
            to perform customization of the output from a Model
            during the assessment process.
        """
        
        #the result
        result = []
        
        if contentZone == "TOOLBAR_TOP" or contentZone == "TOOLBAR_BOTTOM":
        
            displayMode = self.getDisplayMode()
                    
            # Actions
            if assessment:
                user    = self.knowledgeengine_userproviderservice.getAuthenticatedUser()
                actions = [ a for a in assessment.getAssessmentActions( user ) if a.getShowOnAssessmentToolbar() ]
                
                if actions and displayMode == "Dropdown":
                    result.append("""
                        <select onChange="performAction('triggerAssessmentAction', this.value)">
                        <option value="">- Actions -</option>
                    """)
                    
                
                for action in actions:
                    
                    if displayMode == "Buttons":
                        result.append("""
                            <input type="button" class="keButton" value="%s" onClick="performAction('%s', '%s');">
                        """ % ( action.title_or_id(), 'triggerAssessmentAction', action.getIdentity() ))
                        
                    elif displayMode == "Dropdown":
                        result.append("""
                            <option value='%s'>%s</select>
                        """ % ( action.getIdentity(), action.title_or_id() ))
                   
                if actions and displayMode == "Dropdown":
                    result.append( "</select>" )
                   
        return "".join( result )
        
    #---------------------------------------------------------------#
    
    def getDisplayMode(self):
        """ How should actions be displayed """
        
        return getattr(self.aq_explicit, "displayMode", "Buttons")
    
    #---------------------------------------------------------------#

#####################################################################
## Class Initialisation

# Register Class Information with the Knowledge Engine
registerGenericObjectClass(AssessmentActions)

#####################################################################
